<template>
	<main class='abs_full fv'>
		<!-- header -->
		<header class='bcm fx rel i10 nosel' style='height:60px'>
			<div class='fxmc' :style='{width}'><img style='width:150px' :src='Ico_logo'/></div>
			<MenuTopComponent :data='navData' :indexName='indexName' @click='onMainMenuPush' />
			<UserControlComponent :header='ajax.data?.user?.avatar' :name='ajax.data.user.userName' :sub='ajax.data.user.dept' @link='onLink' />
		</header>
		<section class='ex fxs'>
			<!-- left menu -->
			<MenuComponent :data='menuData' :selectedKeys='selectedKeys' :openKeys='openKeys' @click='onSubMenuPush' />
			<!-- right content -->
			<section class='fv ex' style='padding-bottom: 8px;'>
				<!-- router show -->
				<div class='rel jzer-tabs-menu nosel'>
					<header class='cf bcb h abs_full' ref='contextmenu' style='box-shadow: 0 3px 3px #eee;'>
						<Tabs :data='tabData' :value='tabValue' idStr='path' nameStr='title' type='editable-card'
							@close='onClose'
							@change='({ value }) => onTagPush({ path:value })'
						/>
					</header>
				</div>
				<!-- router view -->
				<div class='rel ex' style='margin:0 8px;' :key='key'>
					<router-view v-if='$route.meta.keepAlive!==false' v-slot='{ Component }'>
						<keep-alive>
							<component :is='Component' />
						</keep-alive>
					</router-view>
					<router-view v-else />
					<!-- <router-view/> -->
				</div>
			</section>
		</section>
	</main>
	<ul class='abs_lt bcf i10 contextmenu f12 g3 dn' ref='menuBox'>
		<li class='tap h30 plr10 hover-bc cp' @click.stop='onMenuClose(0)'>关闭左边</li>
		<li class='tap h30 plr10 hover-bc cp' @click.stop='onMenuClose(1)'>关闭右边</li>
		<li class='tap h30 plr10 hover-bc cp' @click.stop='onMenuClose(2)'>关闭其它</li>
		<li class='tap h30 plr10 hover-bc cp' @click.stop='onMenuClose(3)'>关闭所有</li>
	</ul>
</template>

<script setup>
	const Tabs 	= $.lazy(()=>import('@antd/tabs.vue'))
	import { useRoute, useRouter } from 'vue-router'
	/* --------------------------- images --------------------------- */
	import Ico_logo from '@img/frame/logo.png'
	import Ico_arrow from '@img/arrow.png'
	import Img_uer from '@img/user.png'
	/* --------------------------- Sync Component --------------------------- */
	import  MenuComponent from '#frame/cpt/menu.vue'
	/* --------------------------- Async Component --------------------------- */
	const Tag = $.lazy(()=>import('@antd/tag.vue'))
	const MenuTopComponent = $.lazy(()=>import('#frame/cpt/menu-top.vue'))
	const UserControlComponent = $.lazy(()=>import('#frame/cpt/user-control.vue'))
	/* --------------------------- data --------------------------- */
	const route = useRoute()
	const router = useRouter()
	const fn = $fn
	const width = '200px'
	const navData = $fn.session('menu')
	const defaultRouter = navData[0].children[0]
	/* --------------------------- 获取当前路由的所有展开父级 --------------------------- */
	const isOpenAll = false
	const getCurrentOpenKeys = () => {
		const key = location.hash.replace('#','')
		let result = []
		const deep = ( data, parentName) => {
			data.forEach( ({ name, path, children }) => {
				if($fn.hasArray( children )){
					deep( children, name )
				}else{
					if( key === path ){
						result.push( parentName )
					}
				}
			} )
		}
		deep( navData )
		return result
	}
	/* --------------------------- 获取所有 openKeys --------------------------- */
	const getAllOpenKeys = data => {
		let result = []
		const deep = (data, parentName) => {
			data.forEach( ({ children, name }) => {
				if($fn.hasArray(children)){
					deep( children, name )
				}else{
					result.push( parentName )
				}
			})
		}
		deep( navData )
		return result
	}
	
	/* --------------------------- ref --------------------------- */
	let menuData = $ref([])
	let indexName = $ref('')
	let selectedKeys = $ref([])

	let openKeys = $ref( isOpenAll ? getAllOpenKeys() : getCurrentOpenKeys() )
	let key = $ref(0)
	/* --------------------------- 获取用户信息 --------------------------- */
	let ajax = $ref({ data:{user:{}} })
	// $http.pull(ajax,'getInfo').then(data=>{
	// 	const user = $fn.getUser()
	// 	$fn.local('user',{ ...user, ...data.user })
	// })
	/* --------------------------- 选择菜单 --------------------------- */
	const getRedirect = data => {
		if( $fn.hasArray( data ) ){
			let { children } = data[0]
			if( $fn.hasArray(children) ){ return getRedirect( children ) }
			return data[0]
		}
	}
	// 顶部菜单跳转路由
	const onMainMenuPush = value => {
		if(!value) return
		const { children, name } = value
		
		const obj = getRedirect( children )
		
		const { path } = obj
		
		if(path.indexOf('http') !== -1){
			window.open(path)
		}else{
			router.push(path)
			selectedKeys = [ path ]
			menuData = children || []
			indexName = name
			if($fn.hasArray(children)){
				addRouer( obj )
			}
			setTimeout(()=> openKeys = getCurrentOpenKeys() ,200)
		}
	}
	window.refreshRouter = () => key = key + 1
	// 左侧菜单跳转路由
	const onSubMenuPush = value => {
		const { path } = value
		// selectedKeys = [ path ]
		router.push(path)
		addRouer(value)
	}
	const onLink = value => {
		onSubMenuPush(value)
		menuData = navData[navData.length - 1].children
		indexName = name
	}
	/* --------------------------- 监听路由 --------------------------- */
	// 获取路由对应的数据
	const getItems = () => {
		const { path } = route
		let item = null
		const deep = data => {
			data.forEach( v => {
				if(v.path === path && !$fn.hasArray(v.children)){
					item = v
				}else{
					if($fn.hasArray(v.children) && !item){
						deep(v.children)
					}
				}
			})
		}
		deep(navData)
		return item
	}
	
	// 配置路径默认效果
	const getDefaultRouter = path => {
		selectedKeys = [path]
		const arr = navData.filter( v => path.indexOf(('/' + v.name + '/')) !== -1)
		if($fn.hasArray(arr)){
			menuData = arr[0].children 		// 获取默认左侧菜单
			indexName = arr[0].name			// 设置顶部菜单当前选中
		}
	}
	/* --------------------------- 关闭当前选择路由 --------------------------- */
	let tabData = $ref([ defaultRouter ])
	let tabValue = $ref( defaultRouter.path )
	// 添加路由
	const addRouer = row => {
		if(!row) return
		if(row.path !== defaultRouter.path){
			tabData.forEach( ({ path }, i) => {
				if(path === row.path){
					tabData.splice(i, 1)
				}
			} )
			tabData.push(row)
			tabValue = row.path
		}
		selectedKeys = [ row.path ]
	}
	// 删除路由
	const onClose = ({ data, value }) => {
		const lastPath = data[ data.length - 1 ].path
		tabData = data
		tabValue = lastPath
		// 为空时，始终访问工作台
		if(!$fn.hasArray(tabData)){ addRouer(defaultRouter) }
		 // 始终访问最后一个路由
		const {path} = tabData[tabData.length - 1] 			
		router.push(path)
		selectedKeys = [ path ]
		getDefaultRouter(path)
	}
	// 跳转到标签上的路由
	const onTagPush = ({path}) => {
		router.push(path)
		selectedKeys = [ path ]
		getDefaultRouter(path)
		tabValue = path
	}
	/* --------------------------- 默认调用 --------------------------- */
	addRouer(getItems())
	getDefaultRouter(route.path)
	// 快捷操作
	let contextmenu = $ref()
	let menuBox = $ref()
	let index = 0
	const getLastPushRouter = data => {
		// 始终访问最后一个路由
		const {path} = data[data.length - 1]
		router.push(path)
		selectedKeys = [ path ]
		getDefaultRouter(path)
	}
	$.onMounted(()=>{
		window.addEventListener('click',e=>{
			if(menuBox){
				menuBox.style.display = 'none'
			}
			index = 0
		})
		contextmenu.oncontextmenu = function(e){
			const { target } = e
			e.stopPropagation()
			e.preventDefault()
			
			if(target.getAttribute('role') || target.parentNode.getAttribute('role') || target.parentNode.parentNode.getAttribute('role')){
				let node = null
				if(target.getAttribute('role')){
					node = target
				}else if(target.parentNode.getAttribute('role')){
					node = target.parentNode
				}else if(target.parentNode.parentNode.getAttribute('role')){
					node = target.parentNode.parentNode
				}
				index = [].slice.call(node.parentNode.children).findIndex(v => v === node)
				
				const x = e.pageX || e.x || e.screenX || e.clientX
				const y = e.pageY || e.y || e.screenY || e.clientY
				menuBox.style.display = 'block'
				menuBox.style.left = x + 'px'
				menuBox.style.top = y + 'px'
			}else{
				menuBox.style.display = 'none'
				index = 0
			}
		}
	})
	const onMenuClose = i => {
		// 始终访问最后一个路由
		let data = []
		switch(i){
			case 0: 	// 关闭左侧
				if(index > 1){
					data = tabData.filter((v,j) => j >= index )
					data = [defaultRouter, ...data]
				}else{
					menuBox.style.display = 'none'
					return
				}
				break
			case 1:		// 关闭右侧
				if(index < tabData.length - 1){
					data = tabData.filter((v,j) => j <= index )
					getLastPushRouter(data)
				}else{
					menuBox.style.display = 'none'
					return
				}
				break
			case 2: 	// 关闭其它
				if(tabData.length > 2){
					data = tabData.filter((v,j) => j === 0 || j === index )
					getLastPushRouter(data)
				}else{
					menuBox.style.display = 'none'
					return
				}
				break
			case 3:		// 关闭所有
				data = [ defaultRouter ]
				getLastPushRouter(data)
				break
			default:
				break
		}
		tabData = data
		menuBox.style.display = 'none'
	}
	/* --------------------------- 查看源码 --------------------------- */
	
</script>
<style scoped>
	.contextmenu{width:100px;box-shadow: 0 0 8px #bbb;}
</style>